"""
API上下文
为插件提供宿主环境的能力接口
"""

import logging
from typing import Any, Dict, Optional
from .hook_hub import HookHub


class APIContext:
    """
    API上下文
    为插件提供宿主环境的能力接口，如日志、配置、数据库等
    """
    
    def __init__(self, name: str = "DefaultContext") -> None:
        self.name = name
        self._config: Dict[str, Any] = {}
        self._services: Dict[str, Any] = {}
        self._logger = logging.getLogger(f"plugin.{name}")
        self._hook_hub = HookHub()
    
    def get_logger(self, name: Optional[str] = None) -> logging.Logger:
        """
        获取日志记录器
        
        Args:
            name: 日志记录器名称，如果提供则创建子记录器
            
        Returns:
            日志记录器实例
        """
        if name:
            return self._logger.getChild(name)
        return self._logger
    
    def set_config(self, key: str, value: Any) -> None:
        """
        设置配置项
        
        Args:
            key: 配置键
            value: 配置值
        """
        self._config[key] = value
    
    def get_config(self, key: str, default: Any = None) -> Any:
        """
        获取配置项
        
        Args:
            key: 配置键
            default: 默认值
            
        Returns:
            配置值
        """
        return self._config.get(key, default)
    
    def register_service(self, name: str, service: Any) -> None:
        """
        注册服务
        
        Args:
            name: 服务名称
            service: 服务实例
        """
        self._services[name] = service
        self._logger.debug(f"Service registered: {name}")
    
    def unregister_service(self, name: str) -> None:
        """
        注销服务
        
        Args:
            name: 服务名称
        """
        if name in self._services:
            del self._services[name]
            self._logger.debug(f"Service unregistered: {name}")
    
    def get_service(self, name: str) -> Any:
        """
        获取服务
        
        Args:
            name: 服务名称
            
        Returns:
            服务实例，不存在返回None
        """
        return self._services.get(name)
    
    def get_hook_hub(self) -> HookHub:
        """
        获取钩子中心
        
        Returns:
            HookHub实例
        """
        return self._hook_hub
    
    def create_child_context(self, name: str) -> 'APIContext':
        """
        创建子上下文
        
        Args:
            name: 子上下文名称
            
        Returns:
            新的APIContext实例
        """
        child = APIContext(f"{self.name}.{name}")
        # 继承父级配置和服务
        child._config = self._config.copy()
        child._services = self._services.copy()
        return child